// eslint-disable-next-line
import * as loginService from '@/api/login'
// eslint-disable-next-line
import { BasicLayout, RouteView, BlankLayout, PageView ,UserLayout ,BasicLayout_comprehensive ,BasicLayout_revenue ,BasicLayout_factory,BasicLayout_system,BasicLayout_pipe,BasicLayout_customer,BasicLayout_workorder} from '@/layouts'

// 前端路由表
const constantRouterComponents = {
  // 基础页面 layout 必须引入
  BasicLayout: BasicLayout,
  BlankLayout: BlankLayout,
  RouteView: RouteView,
  PageView: PageView,
  UserLayout: UserLayout,
  BasicLayout_comprehensive: BasicLayout_comprehensive,
  BasicLayout_revenue: BasicLayout_revenue,
  BasicLayout_system: BasicLayout_system,

  '403': () => import(/* webpackChunkName: "error" */ '@/views/exception/403'),
  '404': () => import(/* webpackChunkName: "error" */ '@/views/exception/404'),
  '500': () => import(/* webpackChunkName: "error" */ '@/views/exception/500'),

  '/views/system/log': () => import('@/views/system/czLog'),
  '/views/system/personnel': () => import('@/views/system/personnel'),
  '/views/system/dept': () => import('@/views/system/dept'),
  '/views/system/role': () => import('@/views/system/role'),
  '/views/system/userManagement/staffManagement': () => import('@/views/system/userManagement/staffManagement'), // 用户管理-员工管理
  '/views/system/userManagement/user': () => import('@/views/system/userManagement/user'), // 用户管理-个人用户
  '/views/system/userManagement/foreignUser': () => import('@/views/system/userManagement/foreignUser'), // 用户管理-对外用户
  '/views/system/menu': () => import('@/views/system/menu'),
  '/views/system/setting/sysDict': () => import('@/views/system/setting/sysDict'),
  '/views/system/business/punish': () => import('@/views/system/business/punish'), // 企业管理-处罚企业
  '/views/system/business/blowdown': () => import('@/views/system/business/blowdown'), // 企业管理-重点排污

  // 学习管理
  '/views/revenue/home': () => import('@/views/revenue/home'), // 首页
  '/views/revenue/course/courseManagement': () => import('@/views/revenue/course/courseManagement'), // 课程管理-课程列表
  '/views/revenue/course/typeManagement': () => import('@/views/revenue/course/typeManagement'), // 课程管理-类型管理
  '/views/revenue/broadcast/live': () => import('@/views/revenue/broadcast/live'), // 直播管理-直播列表
  '/views/revenue/exam/repo': () => import('@/views/revenue/exam/repo'), // 考试管理-题库管理
  '/views/revenue/exam/qu': () => import('@/views/revenue/exam/qu'), // 考试管理-题目管理
  '/views/revenue/exam/exam': () => import('@/views/revenue/exam/exam'), // 考试管理-考试管理
  '/views/revenue/exam/review': () => import('@/views/revenue/exam/review'), // 考试管理-阅卷管理
  '/views/revenue/invoice/regulationName': () => import('@/views/revenue/invoice/regulationName'), // 资料管理-法规名称
  '/views/revenue/invoice/videoMaterial': () => import('@/views/revenue/invoice/videoMaterial'), // 资料管理-视频资料
  '/views/revenue/invoice/writtenMaterial': () => import('@/views/revenue/invoice/writtenMaterial'), // 资料管理-文字资料
  '/views/revenue/message/info': () => import('@/views/revenue/message/info'), // 消息管理-资讯发布
  '/views/revenue/message/short': () => import('@/views/revenue/message/short'), // 消息管理-短信下发
  '/views/revenue/message/chat': () => import('@/views/revenue/message/chat')// 消息管理-聊天管理

}

// 前端未找到页面路由（固定不用改）
const notFoundRouter = {
  path: '*', redirect: '/404', hidden: true
}

// 根级菜单
// const rootRouter = {
//   key: '',
//   name: 'index',
//   path: '',
//   component: 'BasicLayout',
//   redirect: '/dashboard',
//   meta: {
//     title: '首页'
//   },
//   children: []
// }

/**
 * 动态生成菜单
 * @param token
 * @returns {Promise<Router>}
 */
export const generatorDynamicRouter = (token) => {
  return new Promise((resolve, reject) => {
    loginService.getCurrentUserNav(token).then(res => {
      console.log('res', res)
      // const { result } = res
      const result = res.data
      let menuNav = []
      const childrenNav = []
      //      后端数据, 根级树数组,  根级 PID
      listToTree(result, childrenNav, 0)
      // rootRouter.children = childrenNav
      // menuNav.push(rootRouter)
      menuNav = childrenNav
      console.log('menuNav', menuNav)
      const routers = generator(menuNav)
      routers.push(notFoundRouter)
      console.log('routers', routers)
      resolve(routers)
    }).catch(err => {
      reject(err)
    })
  })
}

/**
 * 格式化树形结构数据 生成 vue-router 层级路由表
 *
 * @param routerMap
 * @param parent
 * @returns {*}
 */
export const generator = (routerMap, parent) => {
  return routerMap.map(item => {
    const { title, show, hideChildren, hiddenHeaderContent, target, icon } = item.meta || {}
    const currentRouter = {
      // 如果路由设置了 path，则作为默认 path，否则 路由地址 动态拼接生成如 /dashboard/workplace
      path: item.path || `${parent && parent.path || ''}/${item.key}`,
      // 路由名称，建议唯一
      name: item.name || item.key || '',
      // 该路由对应页面的 组件 :方案1
      component: constantRouterComponents[item.component || item.key],
      // 该路由对应页面的 组件 :方案2 (动态加载)
      // component: constantRouterComponents[item.component || item.key] || () => import(`@/views/${item.component}`),

      // meta: 页面标题, 菜单图标, 页面权限(供指令权限用，可去掉)
      meta: { title: title, icon: icon || undefined, hiddenHeaderContent: hiddenHeaderContent, target: target, permission: item.name }
    }
    // 是否设置了隐藏菜单
    if (show === false) {
      currentRouter.hidden = true
    }
    // 是否设置了隐藏子菜单
    if (hideChildren) {
      currentRouter.hideChildrenInMenu = true
    }
    // 为了防止出现后端返回结果不规范，处理有可能出现拼接出两个 反斜杠
    if (!currentRouter.path.startsWith('http')) {
      currentRouter.path = currentRouter.path.replace('//', '/')
    }
    // 重定向
    item.redirect && (currentRouter.redirect = item.redirect)
    // 是否有子菜单，并递归处理
    if (item.children && item.children.length > 0) {
      // Recursion
      currentRouter.children = generator(item.children, currentRouter)
    }
    return currentRouter
  })
}

/**
 * 数组转树形结构
 * @param list 源数组
 * @param tree 树
 * @param parentId 父ID
 */
const listToTree = (list, tree, parentId) => {
  list.forEach(item => {
    // 判断是否为父级菜单
    if (item.parentId === parentId) {
      const child = {
        ...item,
        key: item.key || item.name,
        children: []
      }
      // 迭代 list， 找到当前菜单相符合的所有子菜单
      listToTree(list, child.children, item.id)
      // 删掉不存在 children 值的属性
      if (child.children.length <= 0) {
        delete child.children
      }
      // 加入到树中
      tree.push(child)
    }
  })
}
